<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Edit_meals extends CI_Controller {
	public function index()
	{
            $this->load->model('categories');
            $categories = $this->categories->getAll();
            
                $data['title'] = "Manage Meals";
                $data['js'] = array("edit_meals.js");
                $data['data'] = array (
                    "categories"=> $categories,
                    "response" => $this->session->flashdata('meal_response')
                    );
                
                $data['view'] = "meal_editing/view_edit_meals";
                $this->load->view('view_template',$data);
	}
        
        public function previewMeal(){
            //AJAX function
            extract($this->ajax->post("meal_id"));
            
            $this->load->model('meals');
               
            $meal = $this->meals->getMealInfo($meal_id);
            $ingredients = $this->meals->getIngredients($meal_id);
            $categories = $this->meals->getCategories($meal_id);
            
            $data["meal"] = $meal;
            $data["ingredients"] = $ingredients;
            $data["categories"] = $categories;
            $data["test"] = $meal_id;
            
            $this->load->view("ajax/view_preview_meal", $data);
            
        }
        
        public function searchResults(){
            $return = $this->ajax->post("search_term","category");
            extract($return);
            
            $this->load->model('meals');
            $meals = $this->meals->getWhere($search_term, $category);
            
            $options = array();
            
            foreach($meals->result() as $result){
                $options[$result->meal_id] = array(
                    'title'=> $result->meal_title,
                    'desc' => $result->meal_description
                );
            }
            
            $this->load->view("ajax/view_list", 
                array(
                    "options"=>$options,
                    "function"=>"selectMeal"
                )
            );
        }
        
        public function deleteMeal(){
            $meal_id = $this->input->post('meal_id');
            $this->load->model('meals');

            if ($this->meals->isToday($meal_id) && get_role_num() < admin_role()){
                $this->session->set_flashdata('meal_response',"Cannot delete a meal being served today.");
                return;
            }
            

            if ($this->meals->deleteMeal($meal_id)){
                $this->session->set_flashdata('meal_response',"Meal Deleted");
            }
            else{
                $this->session->set_flashdata('meal_response',"An error occurred while deleting the meal.");
            }
        }
}